import { createFilterColumns, createTableRequestParams } from '@/utils/table';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { Button } from 'antd';
import { useMemo, useRef, useState } from 'react';
import api from './request';

export interface Props {
  userId: string;
}
function CustomerCouponLog(props: Props) {
  const { userId } = props;
  const actionRef = useRef<ActionType>();

  const [filterList, setFilterList] = useState<Requestor.FilterResponse[]>([]);

  // request
  const getFilterList = async () => {
    // const filterList = await api.getFilterList();
    const filterList: Requestor.FilterResponse[] = [];
    setFilterList(filterList);
    return filterList;
  };
  const getListRequest = (
    params: Requestor.TableParams,
    filterList: Requestor.FilterResponse[],
  ) => {
    const requestParams = createTableRequestParams(params, filterList);
    return api.getList({ ...requestParams, sortField: 'verificationTime', userId });
  };
  const getList = async (params: Requestor.TableParams) => {
    if (!filterList || !filterList.length) {
      const filterList = await getFilterList();
      return getListRequest(params, filterList);
    } else {
      return getListRequest(params, filterList);
    }
  };

  const columns = useMemo(() => {
    const filterColumns = createFilterColumns<CustomerCouponLog.ListResponse>(filterList);
    const tableColumns: ProColumns<CustomerCouponLog.ListResponse>[] = [
      {
        title: '优惠券名称',
        dataIndex: 'name',
        ellipsis: true,
        hideInSearch: true,
        align: 'center',
      },
      {
        title: '核销码',
        dataIndex: 'verificationCode',
        ellipsis: true,
        hideInSearch: true,
        align: 'center',
      },
      {
        title: '核销时间',
        dataIndex: 'verificationTime',
        ellipsis: true,
        hideInSearch: true,
        align: 'center',
      },
    ];
    return filterColumns.concat(tableColumns);
  }, [filterList]);
  return (
    <ProTable
      bordered
      size="small"
      rowKey="id"
      options={false}
      actionRef={actionRef}
      pagination={{ defaultPageSize: 10, showSizeChanger: true }}
      toolBarRender={() => []}
      search={{
        optionRender: () => {
          return [
            <Button key="search" type="primary" onClick={() => actionRef.current?.reload()}>
              查询
            </Button>,
          ];
        },
      }}
      columns={columns}
      request={getList}
    />
  );
}

export default CustomerCouponLog;
